package com.xjm.api.web;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xjm.entity.model.CartItemsModel;
import com.xjm.entity.model.ProductsModel;
import com.xjm.entity.vo.Result;
import com.xjm.service.ICartItemsService;
import com.xjm.service.IProductsService;
import com.xjm.utils.UserContext;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author xjm
 * @since 2025-03-01
 */
@RestController
@RequestMapping("/user/cartItem")
@RequiredArgsConstructor
public class WebCartItemsController {

    private final ICartItemsService cartItemsService;
    private final IProductsService productsService;

    @GetMapping
    public Result<List<CartItemsModel>> list() {
        Integer userId = UserContext.getUserId();
        List<CartItemsModel> list = cartItemsService.list(new LambdaQueryWrapper<CartItemsModel>().eq(CartItemsModel::getUserId, userId));
        list.forEach(cartItemsModel -> {
            cartItemsModel.setProduct(productsService.getById(cartItemsModel.getProductId()));
        });
        return Result.success(list);
    }

    @PostMapping("/{productId}")
    public Result<CartItemsModel> add(@PathVariable String productId) {
        CartItemsModel cartItemsModel;
        Integer userId = UserContext.getUserId();
        LambdaQueryWrapper<CartItemsModel> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CartItemsModel::getUserId, userId);
        queryWrapper.eq(CartItemsModel::getProductId, productId);
        cartItemsModel = cartItemsService.getOne(queryWrapper);
        if (cartItemsModel != null) {
            cartItemsModel.setQuantity(cartItemsModel.getQuantity() + 1);
        } else {
            cartItemsModel = new CartItemsModel();
            cartItemsModel.setUserId(userId);
            cartItemsModel.setProductId(Integer.parseInt(productId));
            cartItemsModel.setSelected(1);
            cartItemsModel.setQuantity(1);
        }
        cartItemsService.saveOrUpdate(cartItemsModel);
        return Result.success();
    }

    @DeleteMapping("/{cartId}")
    public Result<CartItemsModel> delete(@PathVariable String cartId) {
        Integer userId = UserContext.getUserId();
        LambdaQueryWrapper<CartItemsModel> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CartItemsModel::getUserId, userId);
        queryWrapper.eq(CartItemsModel::getId, cartId);
        cartItemsService.remove(queryWrapper);
        return Result.success();
    }

    @PutMapping("/{cartId}")
    public Result<Void> updateSelected(@PathVariable String cartId, @RequestBody CartItemsModel cartItemsModel) {
        cartItemsModel.setId(Integer.parseInt(cartId));
        cartItemsService.updateById(cartItemsModel);
        return Result.success();
    }

    @PutMapping("/all/{selected}")
    public Result<Void> updateSelectedAll(@PathVariable String selected) {
        Integer userId = UserContext.getUserId();
        LambdaQueryWrapper<CartItemsModel> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CartItemsModel::getUserId, userId);
        CartItemsModel cartItemsModel = new CartItemsModel();
        cartItemsModel.setSelected(Integer.parseInt(selected));
        cartItemsService.update(cartItemsModel, queryWrapper);
        return Result.success();
    }

    @PutMapping("/{cartId}/{quantity}")
    public Result<Void> updateQuantity(@PathVariable Integer cartId, @PathVariable Integer quantity) {
        CartItemsModel cartItemsModel = new CartItemsModel();
        cartItemsModel.setId(cartId);
        cartItemsModel.setQuantity(quantity);
        cartItemsService.updateById(cartItemsModel);
        return Result.success();
    }

    @PostMapping("/checkout")
    public Result<List<CartItemsModel>> checkout(@RequestBody JSONObject data) {
        Integer userId = UserContext.getUserId();
        List<Integer> ids = data.getJSONArray("ids").stream().map(i -> (Integer) i).toList();
        LambdaQueryWrapper<CartItemsModel> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CartItemsModel::getUserId, userId);
        queryWrapper.in(CartItemsModel::getId, ids);
        List<CartItemsModel> result = cartItemsService.list(queryWrapper);
        result.forEach(cartItemsModel -> cartItemsModel.setProduct(productsService.getById(cartItemsModel.getProductId())));
        return Result.success(result);
    }
}
